import React, { memo, useEffect, useState } from 'react';
import Zoomable from '@/components/zoomable';
import styles from './index.less';
import useRealtimeMessage from '../../useModels/useRealtimeMessage';
import moment from 'moment';
import { createSocket } from '../Toolbar';

const RealtimeMessage = memo(() => {
  let bodyHeight = document.body.offsetHeight;
  let bodyWidth = document.body.offsetWidth;

  const {
    visible,
    record = [],
    setVisible,
    clearRecord,
    closeSocket,
    updateRecord,
    dispatch,
    socket,
  } = useRealtimeMessage(model => [model.visible, model.socket, model.record]);
  const onClose = () => {
    closeSocket(socket);
  };
  useEffect(() => {
    return () => {
      setVisible(false);
    };
  }, []);

  if (!visible) {
    return null;
  }
  const testOption = {
    zoomable: {
      width: {
        min: 200, //default 10 拉伸最小宽度
        max: (bodyWidth && bodyWidth) || 1000, //default 1000 拉伸最大宽度
      },
      height: {
        min: 200, //default 10 拉伸最小高度
        max: (bodyHeight && bodyHeight) || 500, //default 500 拉伸最大高度
      },
    },
    defaultWidth: 800,
    defaultHeight: 500,
    onZoomStart: result => {
      // console.log('onZoomStart', result);
    },
    onZoomEnd: result => {
      // console.log('onZoomEnd', result);
    },
    onZooming: result => {
      // console.log('onZooming', result);
    },
  };
  return (
    <>
      {visible && (
        <Zoomable
          used={true}
          onClose={onClose}
          onStop={() => {
            if (socket) {
              socket.disconnect();
              dispatch({ socket: null });
            }
          }}
          onStart={() => {
            if (!socket) {
              createSocket(updateRecord, dispatch);
            }
          }}
          onClear={clearRecord}
          className={styles['real-time-message-box']}
          {...testOption}
        >
          <div className={styles['logs-wrap']}>
            {record.map((item, index) => {
              return (
                <div
                  key={index.toString(36) + index}
                  title={item.msg}
                  className={styles['logs-item']}
                >
                  <span className={styles['time']}>
                    {moment(Number(item.time)).format('YYYY-MM-DD HH:mm:ss')}
                  </span>
                  <span className={styles['separator']}>-</span>
                  <span className={styles['message']}>{item.msg}</span>
                </div>
              );
            })}
          </div>
        </Zoomable>
      )}
    </>
  );
});
export default RealtimeMessage;
